package controller;

import Pojo.User;
import Pojo.Userlist;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import service.UserService;
import service.UserlistService;

@Controller
public class UserController
{

  @Autowired
  private UserService userService;

  @Autowired
  private UserlistService userlistService;

  @RequestMapping({"/regist"})
  @ResponseBody
  public Map<Object, Object> regist(String userName, String passWord, HttpServletResponse response)
  {
    Map map = new HashMap();
    try {
      if ((userName == null) || 
        ("".equals(userName)) || (passWord == null) || ("".equals(passWord))) {
        map.put("success", Boolean.valueOf(false));
        map.put("message", "账号或密码不能为空");
        return map;
      }
      this.userService.regist(userName, passWord);
      map.put("success", Boolean.valueOf(true));
    }
    catch (Exception e) {
      map.put("success", Boolean.valueOf(false));
      map.put("msg", e.getMessage());
    }
    return map;
  }

  @RequestMapping({"/login"})
  public String userList() throws Exception
  {
    return "login";
  }

  @RequestMapping({"/logincheck"})
  public String login(User user, Model model, HttpSession httpSession) throws Exception
  {
    User user1 = this.userService.login(user);

    if (user1 != null) {
      httpSession.setAttribute("user", user1);
      if (user1.getType().equals("zuke")) {
        User user2 = (User)httpSession.getAttribute("user");
        Integer user_id = user2.getId();
        Userlist userlist = this.userlistService.findhasuserlist(user_id);
        model.addAttribute("userlist", userlist);
        model.addAttribute("mainPage", "updateuserlist.jsp");
        return "zuke/main";
      }

      return "admin/main1";
    }

    String error = "error";
    model.addAttribute("error", error);
    return "login";
  }

  @RequestMapping({"/toindex"})
  public String toindex(Model model)
    throws Exception
  {
    return "admin/index";
  }
}